import React, { useEffect, useState } from 'react';
import { getAvailableVoices, useVoiceStore, initVoices } from '../utils/textToSpeech';

interface AudioButtonProps {
  accent: 'US' | 'UK';
  text: string;
  onClick: () => void;
}

export const AudioButton: React.FC<AudioButtonProps> = ({ accent, text, onClick }) => {
  const [mounted, setMounted] = useState(false);
  const isInitialized = useVoiceStore((state) => state.isInitialized);
  const voices = useVoiceStore((state) => state.voices);

  useEffect(() => {
    setMounted(true);
    if (!isInitialized) {
      initVoices();
    }
  }, []);

  useEffect(() => {
    if (mounted && !isInitialized && voices.length === 0) {
      initVoices();
    }
  }, [mounted, isInitialized, voices]);

  if (!mounted || !isInitialized || !getAvailableVoices(accent)) {
    return null;
  }

  return (
    <button
      onClick={onClick}
      className="inline-flex items-center px-2 py-1 mr-2 text-xs text-gray-600 bg-gray-100 rounded hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300"
      title={`Play with ${accent} accent`}
    >
      <svg
        className="w-3 h-3 mr-1"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"
        />
      </svg>
      {accent}
    </button>
  );
}